package com.landinfo.web.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.codahale.metrics.annotation.Timed;
import com.esri.core.geometry.*;
import com.landinfo.config.GeometryUtil;
import com.landinfo.domain.GpsLocation;
import com.landinfo.service.GpsLocationService;
import com.landinfo.service.dto.GpsLocationDTO;
import com.landinfo.service.mapper.GpsLocationMapper;
import com.landinfo.web.rest.util.HeaderUtil;
import com.vividsolutions.jts.geom.Point;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.*;

/**
 * Created by ziqilv on 2017/7/22.
 */
@RestController
@RequestMapping("/api/gps")
public class GpsLocationResource {
    private final Logger log = LoggerFactory.getLogger(DataTypeResource.class);

    private static final String ENTITY_NAME = "dataType";

    private java.text.SimpleDateFormat dateTimeFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private java.text.SimpleDateFormat dateTimeFormatStart = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:00");
    private java.text.SimpleDateFormat dateTimeFormatStart1 = new java.text.SimpleDateFormat("yyyy-MM-dd 00:00:00");
    private java.text.SimpleDateFormat dateTimeFormatEnd = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:59");

    private final GpsLocationService gpsLocationService;
    private final GpsLocationMapper gpsLocationMapper;

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private GeometryUtil geometryUtil;

    public GpsLocationResource(GpsLocationService gpsLocationService, GpsLocationMapper gpsLocationMapper) {
        this.gpsLocationService = gpsLocationService;
        this.gpsLocationMapper = gpsLocationMapper;
    }

    /**
     * POST  /data-types : Create a new dataType.
     *
     * @param gpsLocationDTO the GpsLocationDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new GpsLocationDTO, or with status 400 (Bad Request) if the dataType has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/create")
    @Timed
    public ResponseEntity<GpsLocationDTO> create(@Valid @RequestBody GpsLocationDTO gpsLocationDTO) throws URISyntaxException {
        log.debug("REST request to save DataType : {}", gpsLocationDTO);

        GpsLocationDTO result = gpsLocationService.save(gpsLocationDTO);
        return ResponseEntity.created(new URI("/api/gps/" + result.getId()))
                .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
                .body(result);
    }

    /**
     * 导入Gps点集
     *
     * @param gpsLocationDTOs
     * @return
     * @throws URISyntaxException
     */
    @PostMapping("/import")
    @Timed
    public Integer importGps(@Valid @RequestBody List<GpsLocationDTO> gpsLocationDTOs) throws URISyntaxException {
        log.debug("REST request to save DataType : {}", gpsLocationDTOs);
        if (gpsLocationDTOs == null || gpsLocationDTOs.size() <= 0) {
            return -1;
        }
        gpsLocationService.deleteByParentId(gpsLocationDTOs.get(0).getParentId());
        Integer result = gpsLocationService.saveAll(gpsLocationDTOs);
        return result;
    }

    /**
     * 创建模板（表单）
     *
     * @return
     */
    @Transactional
    @PostMapping("/save-distance")
    @Timed
    public String saveDynamicTable(@Valid @RequestBody GpsLocationDTO gpsLocationDTO) {
        HashMap<String, Object> result = new HashMap<>();
        try {
            List<GpsLocationDTO> gpsLocationDTOS = getNewDeviceByParentId(gpsLocationDTO.getParentId());
            if (gpsLocationDTOS != null && gpsLocationDTOS.size() > 0) {
                Polyline polyline = new Polyline();
                Transformation2D transformation2D = new Transformation2D();

                polyline.applyTransformation(transformation2D);
                double totalDistance = 0;
                for (int i = 0; i < gpsLocationDTOS.size(); i++) {
                    GpsLocationDTO gpsPoint = gpsLocationDTOS.get(i);
                    if (i == 0) {
                        polyline.startPath(gpsPoint.getX(), gpsPoint.getY());
                    } else {
                        polyline.lineTo(gpsPoint.getX(), gpsPoint.getY());
                        totalDistance += GeometryEngine.geodesicDistanceOnWGS84(polyline.getPoint(i - 1), polyline.getPoint(i));
                    }
                }
                //double length = polyline.calculateLength2D();
                String sql = String.format("update %s set %s=%f where id='%s'", gpsLocationDTO.getDynamicTableName(), gpsLocationDTO.getAuthor() + "Length", totalDistance, gpsLocationDTO.getId());
                Query query = entityManager.createNativeQuery(sql);
                int updateCount = query.executeUpdate();
                result.put("success", true);
            } else {
                result.put("success", false);
                result.put("message", "未查询到Gps点集，无法计算距离");
            }
            return JSON.toJSONString(result);
        } catch (Exception ex) {
            result.put("success", false);
            result.put("message", "错误：" + ex.getLocalizedMessage());
            return JSON.toJSONString(result);
        }
    }


    /**
     * PUT  /data-types : Updates an existing dataType.
     *
     * @param GpsLocationDTO the GpsLocationDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated GpsLocationDTO,
     * or with status 400 (Bad Request) if the GpsLocationDTO is not valid,
     * or with status 500 (Internal Server Error) if the GpsLocationDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/update")
    @Timed
    public ResponseEntity<GpsLocationDTO> update(@Valid @RequestBody GpsLocationDTO GpsLocationDTO) throws URISyntaxException {
        log.debug("REST request to update DataType : {}", GpsLocationDTO);
        if (GpsLocationDTO.getId() == null) {
            return create(GpsLocationDTO);
        }
        GpsLocationDTO result = gpsLocationService.save(GpsLocationDTO);
        return ResponseEntity.ok()
                .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, GpsLocationDTO.getId().toString()))
                .body(result);
    }

    /**
     * GET  /data-types : get all the dataTypes.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of dataTypes in body
     */
    @GetMapping("/getAll")
    @Timed
    public List<GpsLocationDTO> getAllDataTypes() {
        log.debug("REST request to get all DataTypes");
        //com.vividsolutions.jts.geom.Line
        return gpsLocationService.findAll();
    }

    /**
     * GET  获取最近一分钟的gps点位信息
     *
     * @return the ResponseEntity with status 200 (OK) and the list of dataTypes in body
     */
    @GetMapping("/getOneMinutesPatrolGpsLocation")
    @Timed
    public String getOneMinutesPatrolGpsLocation() {
        log.debug("REST request to get all DataTypes");
        long time = 1 * 60 * 1000;//1分钟
        java.util.Date currentDateTime = new java.util.Date();
        Date beforeDate = new Date(currentDateTime.getTime() - time);//30分钟前的时间

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("serviceTime", new Date());

        String sql = String.format("from GpsLocation t WHERE t.createDateTime between '%s' and '%s' ORDER BY t.createDateTime desc", dateTimeFormat.format(beforeDate), dateTimeFormatEnd.format(currentDateTime));
        Query query = entityManager.createQuery(sql, GpsLocation.class);
        List<GpsLocation> gpsLocations = query.getResultList();
        if (gpsLocations != null && gpsLocations.size() > 0) {
            hashMap.put("result", gpsLocations);
            //return JSON.toJSONStringWithDateFormat(gpsLocations, "yyyy-MM-dd HH:mm:ss", SerializerFeature.DisableCircularReferenceDetect);
        } else {
            hashMap.put("result", null);
        }
        return JSON.toJSONStringWithDateFormat(hashMap, "yyyy-MM-dd HH:mm:ss", SerializerFeature.DisableCircularReferenceDetect);
        //return new ResponseEntity<>(gpslocationM.regionsToRegionDTOs(userList), HttpStatus.OK);
    }

    /**
     * GET  获取今天在线的设备信息
     *
     * @return the ResponseEntity with status 200 (OK) and the list of dataTypes in body
     */
    @GetMapping("/getTodayPatrolGpsLocation")
    @Timed
    public String getTodayPatrolGpsLocation() {
        log.debug("REST request to get all DataTypes");
        long time = 1 * 60 * 1000;//1分钟
        java.util.Date currentDateTime = new java.util.Date();

        Date beforeDate = null;     //今天凌晨
        try {
            beforeDate = this.dateTimeFormatStart1.parse(this.dateTimeFormatStart1.format(currentDateTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("serviceTime", new Date());
        String sql = String.format("from GpsLocation t WHERE t.createDateTime between '%s' and '%s' order by t.parentId,t.createDateTime desc", dateTimeFormat.format(beforeDate), dateTimeFormatEnd.format(currentDateTime));

        Query query = entityManager.createQuery(sql, GpsLocation.class);
        List<GpsLocation> gpsLocations = query.getResultList();
        if (gpsLocations != null && gpsLocations.size() > 0) {
            hashMap.put("result", gpsLocations);
        } else {
            hashMap.put("result", null);
        }
        return JSON.toJSONStringWithDateFormat(hashMap, "yyyy-MM-dd HH:mm:ss", SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 根据parentId获取Gps轨迹
     *
     * @param parentId
     * @return
     */
    @GetMapping("/getNewDeviceByParentId/{parentId}")
    @Timed
    public List<GpsLocationDTO> getNewDeviceByParentId(@PathVariable String parentId) {

        String sql = String.format("from GpsLocation t WHERE t.parentId='%s' ORDER BY t.createDateTime desc", parentId);
        Query query = entityManager.createQuery(sql, GpsLocation.class);
        List<GpsLocation> gpsLocations = query.getResultList();
        if (gpsLocations != null && gpsLocations.size() > 0) {
            return gpsLocationMapper.toDto(gpsLocations);
        } else {
            return null;
        }
        //return new ResponseEntity<>(gpslocationM.regionsToRegionDTOs(userList), HttpStatus.OK);
    }

    /**
     * 根据parentId获取Gps轨迹
     *
     * @param parentIds
     * @return
     */
    @PostMapping("/getNewDeviceByParentIds")
    @Timed
    public List<GpsLocationDTO> getNewDeviceByParentIds(@RequestBody String[] parentIds) {
        if (parentIds == null) {
            return null;
        }
        String para = "";
        for (int i = 0; i < parentIds.length; i++) {
            if (i == 0) {
                para += "'" + parentIds[i] + "'";
            } else {
                para += ",'" + parentIds[i] + "'";
            }
        }
        String sql = String.format("from GpsLocation t WHERE t.parentId in (%s) ORDER BY t.createDateTime desc", para);
        Query query = entityManager.createQuery(sql, GpsLocation.class);
        List<GpsLocation> gpsLocations = query.getResultList();
        if (gpsLocations != null && gpsLocations.size() > 0) {
            return gpsLocationMapper.toDto(gpsLocations);
        } else {
            return null;
        }
        //return new ResponseEntity<>(gpslocationM.regionsToRegionDTOs(userList), HttpStatus.OK);
    }

    /**
     * GET  /data-types/:id : get the "id" dataType.
     *
     * @param id the id of the GpsLocationDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the GpsLocationDTO, or with status 404 (Not Found)
     */
    @GetMapping("/get/{id}")
    @Timed
    public ResponseEntity<GpsLocationDTO> getGpsLocation(@PathVariable String id) {
        log.debug("REST request to get DataType : {}", id);
        GpsLocationDTO gpsLocationDTO = gpsLocationService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(gpsLocationDTO));
    }


    /**
     * 测试保存一个点位
     * @return
     */
    @GetMapping("/testsave")
    @Timed
    public Boolean testSaveGpsLocation() {
        GpsLocationDTO gpsLocationDTO = new GpsLocationDTO();
        gpsLocationDTO.setX(103.111);
        gpsLocationDTO.setY(31.00011);
        Point point= geometryUtil.createPoint(gpsLocationDTO.getX(),gpsLocationDTO.getY(),4326);
        gpsLocationDTO.setGeom(point);
        GpsLocationDTO tempGps = gpsLocationService.save(gpsLocationDTO);
        if (tempGps == null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * DELETE  /data-types/:id : delete the "id" dataType.
     *
     * @param id the id of the GpsLocationDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/delete/{id}")
    @Timed
    public ResponseEntity<Void> deleteDataType(@PathVariable String id) {
        log.debug("REST request to delete DataType : {}", id);
        gpsLocationService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }
}
